package com.baosight.risk.service.rire.impl;

/**
 * @Author phinxe
 * @Date 2019-12-11
 */

import com.baosight.risk.api.fltd.FlaaNodeAuthoService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.rire.RireRiskWarningStatusService;
import com.baosight.risk.api.rire.RiwaRiskWaringService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.fltd.FlaaNodeAuthoMapper;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.rire.RireRiskEventMapper;
import com.baosight.risk.mapper.rire.RireRiskTargetMapper;
import com.baosight.risk.mapper.rire.RireRiskWarningStatusMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringRuleMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringStatusMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringTargetMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.fltd.vo.NodeTransitionVO;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.rire.entity.RireRiskEvent;
import com.baosight.risk.service.rire.entity.RireRiskTarget;
import com.baosight.risk.service.rire.entity.RireRiskWarningStatus;
import com.baosight.risk.service.rire.vo.RiskWarningStatusVO;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaring;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringRule;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringStatus;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringTarget;
import com.baosight.risk.service.riwa.vo.RiwaRiskWaringRuleVO;
import com.baosight.risk.service.riwa.vo.RiwaRiskWaringVO;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 重点风险披露报告接口实现
 */
@Service
@Slf4j
public class RireRiskWarningStatusServiceImpl extends BaseServiceImpl<RireRiskWarningStatus> implements RireRiskWarningStatusService {
    @Autowired
    private RireRiskWarningStatusMapper mapper;
    @Autowired
    private RireRiskTargetMapper targetMapper;
    @Autowired
    private RireRiskEventMapper eventMapper;
    @Autowired
    private RiwaRiskWaringMapper modelMapper;
    @Autowired
    private RiwaRiskWaringStatusMapper statusMapper;
    @Autowired
    private RiwaRiskWaringRuleMapper ruleMapper;
    @Autowired
    private RiwaRiskWaringTargetMapper ruleTargetMapper;

    @Autowired
    private FltdTaskMapper fltdTaskMapper;

    @Autowired
    private RireRiskEventMapper rireRiskEventMapper;

    @Autowired
    private RiwaRiskWaringMapper riwaRiskWaringMapper;

    @Autowired
    private RiwaRiskWaringStatusMapper riwaRiskWaringStatusMapper;

    @Autowired
    private RiwaRiskWaringRuleMapper riwaRiskWaringRuleMapper;

    @Autowired
    private RiwaRiskWaringTargetMapper riwaRiskWaringTargetMapper;

    @Autowired
    private FlaaNodeAuthoMapper flaaNodeAuthoMapper;
    @Autowired
    private FlaaNodeAuthoService flaaNodeAuthoService;

    @Autowired
    private RiwaRiskWaringService waringService;

    @Autowired
    private RireRiskWarningStatusMapper rireRiskWarningStatusMapper;

    @Autowired
    private RiimRiskImportMapper riskImportMapper;

    @Autowired
    private XtzyUserMapper xtzyUserMapper;

    @Autowired
    private FltdProcessService fltdProcessService;

    // region 查询相关业务

    /**
     * 根据ID获取披露报告VO
     *
     * @param id 披露报告ID
     * @return
     */
    @Override
    public RiskWarningStatusVO getWarningById(String id) {
        RiskWarningStatusVO result = mapper.getWarningById(id);
        return result;
    }

    @Override
    public Map<String, Object> getReportById(String id) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        // 获取披露报告主体信息(实体VO)
        RiskWarningStatusVO reportVO = getWarningById(id);
        if (reportVO == null) {
            throw new Exception("披露报告不存在，请检查数据！");
        }
        result.put("report", reportVO);
        // 获取披露报告指标信息(列表)
        List<RireRiskTarget> targetList = getTargetList(reportVO.getId());
        //增加默认排序
        if (BeanUtils.sortList(targetList)) {
            for (RireRiskTarget rireRiskTarget : targetList) {
                RireRiskTarget param = new RireRiskTarget();
                param.setId(rireRiskTarget.getId());
                param.setRowOrder(rireRiskTarget.getRowOrder());
                targetMapper.updateByPrimaryKeySelective(rireRiskTarget);
            }
        }
        result.put("targetList", targetList);
        // 获取披露报告事件信息(列表)
        List<RireRiskEvent> eventList = getEventList(reportVO.getId());
        //增加默认排序
        if (BeanUtils.sortList(eventList)) {
            for (RireRiskEvent rireRiskEvent : eventList) {
                eventMapper.updateByPrimaryKeySelective(rireRiskEvent);
            }
        }
        result.put("eventList", eventList);
        // 获取披露报告模型信息(实体)
        Object model = getModel(reportVO.getId(), false);
        result.put("model", model);
        return result;
    }

    /**
     * 根据露报告ID查询重点风险指标集合
     *
     * @param reportId 披露报告ID
     * @return
     */
    @Override
    public List<RireRiskTarget> getTargetList(String reportId) {
        List<RireRiskTarget> list = targetMapper.getTargetByImportId(reportId);
        return list;
    }

    /**
     * 根据露报告ID查询重点风险事件集合
     *
     * @param reportId 披露报告ID
     * @return
     */
    @Override
    public List<RireRiskEvent> getEventList(String reportId) {
        return eventMapper.getEventByImportId(reportId);
    }

    /**
     * 根据露报告ID查询模型
     *
     * @param reportId 披露报告ID
     * @return
     */
    @Override
    public Object getModel(String reportId, Boolean commonFlag) {
        List<RiwaRiskWaring> list = modelMapper.getWaringByImportId(reportId);
        // 实际中一个披露报告对应一个模型，所以这里只取第一个
        if (CollectionUtils.isNotEmpty(list)) {
            RiwaRiskWaring model = list.get(0);
            Object result;
            // region 常规模型 总共四个层级 模型 -> 预警状态 -> 预警规则 -> 预警指标
            if (model.getWarningType().equals("common") || commonFlag) {
                // ———— 层级：第一级  (模型)
                RiwaRiskWaringVO modelVO = new RiwaRiskWaringVO();
                // 为VO赋基本值
                BeanUtils.copyBeanProp(modelVO, model);
                // 获取模型预警状态(绿、黄、橙、红、黑)
                List<RiwaRiskWaringStatus> modelStatusList = mapper.getWaringStatusByReportId(reportId);
                // 获取模型预警规则(对应每个状态中有几个规则)
                List<RiwaRiskWaringRule> modelRuleList = mapper.getWaringRuleByReportId(reportId);
                // 获取模型预警指标(这里是实际的预警值)
                List<RiwaRiskWaringTarget> modelTargetList = mapper.getWaringTargetByReportId(reportId);
                // region 为模型子表填充数据
                if (CollectionUtils.isNotEmpty(modelStatusList)) {
                    List<RiwaRiskWaringVO.RiwaRiskWaringStatusVO> modelStatusVOList = new ArrayList<>();
                    // 循环填充预警状态(这里最大长度应该是5条数据，对应绿、黄、橙、红、黑，超过就不对了。)
                    for (RiwaRiskWaringStatus status : modelStatusList) {
                        // ———— 层级：第二级  (预警状态)
                        RiwaRiskWaringVO.RiwaRiskWaringStatusVO statusVO = new RiwaRiskWaringVO.RiwaRiskWaringStatusVO();
                        // 填充单个预警状态
                        BeanUtils.copyBeanProp(statusVO, status);
                        if (CollectionUtils.isNotEmpty(modelRuleList)) {
                            // 从规则集合中找到当前状态的所有规则
                            List<RiwaRiskWaringRule> statusRules = modelRuleList.stream()
                                    .filter(r -> StringUtils.equals(r.getWaringStatusGuid(), status.getId()))
                                    .collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(statusRules)) {
                                // ———— 层级：第三级  (预警规则)
                                List<RiwaRiskWaringRuleVO> ruleVOList = new ArrayList<>();
                                // 循环填充预警规则
                                for (RiwaRiskWaringRule rule : statusRules) {
                                    RiwaRiskWaringRuleVO ruleVO = new RiwaRiskWaringRuleVO();
                                    // 填充单个预警规则
                                    BeanUtils.copyBeanProp(ruleVO, rule);
                                    // ———— 层级：第四级  (预警指标)
                                    // 从预警指标集合中找到当前规则中所有的预警指标
                                    List<RiwaRiskWaringTarget> ruleTargets = modelTargetList.stream()
                                            .filter(r -> StringUtils.equals(r.getWarningRuleId(), rule.getId()))
                                            .collect(Collectors.toList());
                                    // 填充单个预警规则中所有的预警指标(预警指标已经到最子级，下面没有了)
                                    ruleVO.setRiskWaringTargetList(ruleTargets);
                                    ruleVOList.add(ruleVO);
                                }
                                statusVO.setRiskWaringRuleVOList(ruleVOList);
                            }
                        }
                        modelStatusVOList.add(statusVO);
                    }
                    // 为VO赋预警状态值
                    modelVO.setRiskWaringStatusVOList(modelStatusVOList);
                }
                // endregion
                result = modelVO;
            }
            // endregion
            // region 自定义模型
            else {
                result = model;
            }
            // endregion
            return result;
        }
        return null;
    }
    // endregion

    // region 修改相关业务

    /**
     * 修改披露报告
     *
     * @param report 披露报告
     * @return
     */
    @Override
    public Boolean updateWarning(RireRiskWarningStatus report) {
        BeanUtils.updateBean(report);
        return mapper.updateByPrimaryKey(report) > 0;
    }

    /**
     * 修改披露报告风险指标
     *
     * @param targets 风险指标集合
     * @return
     */
    @Override
    public List<RireRiskTarget> updateTarget(List<RireRiskTarget> targets) {
        List<RireRiskTarget> result = new ArrayList<>();
        for (RireRiskTarget target : targets) {
            // 如果不存在，则新增，否则修改
            if (targetMapper.selectByPrimaryKey(target.getId()) == null) {
                BeanUtils.initBean(target);
                if (targetMapper.insert(target) < 1) {
                    log.error("披露报告风险指标新增失败！");
                }
            } else {
                BeanUtils.updateBean(target);
                if (targetMapper.updateByPrimaryKey(target) < 1) {
                    log.error("披露报告风险指标修改失败！");
                }
            }
            result.add(target);
        }
        return result;
    }

    /**
     * 修改披露报告风险事件
     *
     * @param events 风险事件集合
     * @return
     */
    @Override
    public List<RireRiskEvent> updateEvent(List<RireRiskEvent> events) {
        List<RireRiskEvent> result = new ArrayList<>();
        for (RireRiskEvent event : events) {
            // 如果不存在，则新增，否则修改
            if (eventMapper.selectByPrimaryKey(event.getId()) == null) {
                //生成编码
                BeanUtils.initBean(event);
                String importReportGuidStr = event.getImportReportGuid().substring(0, 8);
                Integer count = eventMapper.getCountByImportReportGuid(event.getImportReportGuid());
                count++;
                event.setExt2(event.getAcctYear() + importReportGuidStr + count);
                if (eventMapper.insert(event) < 1) {
                    log.error("披露报告风险事件新增失败！");
                }
            } else {
                BeanUtils.updateBean(event);
                if (eventMapper.updateByPrimaryKey(event) < 1) {
                    log.error("披露报告风险事件修改失败！");
                }
            }
            result.add(event);
        }
        return result;
    }

    /**
     * 修改披露报告模型
     *
     * @param modelVO 披露报告模型
     * @return
     */
    @Override
    public Object updateModel(RiwaRiskWaringVO modelVO) {
        // 先获取模型的ID ，这里因为前端上传附件需要所以由前端生成ID
        String modelId = modelVO.getId();
        RiwaRiskWaring model = new RiwaRiskWaring();
        BeanUtils.copyBeanProp(model, modelVO);
        Boolean result = false;
        // 是新增还是修改
        if (modelMapper.selectByPrimaryKey(modelVO.getId()) == null) {

            BeanUtils.initBean(model);
            // 设置ID为前端生成的ID
            model.setId(modelId);
            if (modelMapper.insert(model) < 1) {
                log.error("披露报告模型新增失败！");
                return null;
            }
            result = true;

        } else {
            RireRiskWarningStatus updateParam = new RireRiskWarningStatus();
            updateParam.setImportGuid(model.getImportGuid());
            updateParam.setAcctYear(model.getAcctYear());
            List<RireRiskWarningStatus> rireRiskWarningStatusList =  rireRiskWarningStatusMapper.getWarningStatusByImportIdAndYear(model.getImportGuid(),model.getAcctYear());
            List<String> codeStr = new ArrayList<String>();
            for(RireRiskWarningStatus warningStatusrire:rireRiskWarningStatusList){
                if(!codeStr.contains(warningStatusrire.getQuarterCode())){
                    codeStr.add(warningStatusrire.getQuarterCode());
                }
            }
           /* if(codeStr.size()>1){
                log.error("同年度已经有披露报告模型，修改失败！");
                return "f";
            }*/
            BeanUtils.updateBean(model);
            if (modelMapper.updateByPrimaryKey(model) < 1) {
                log.error("披露报告模型修改失败！");
                return null;
            }
            result = true;
        }
        // region 常规模型 总共四个层级 模型 -> 预警状态 -> 预警规则 -> 预警指标
        if (model.getWarningType().equals("common")) {
            // 模型预警状态
            for (RiwaRiskWaringVO.RiwaRiskWaringStatusVO statusVO : modelVO.getRiskWaringStatusVOList()) {
                // 如果预警状态下规则为空，则删除预警状态
                if (statusVO.getRiskWaringRuleVOList().size() <= 0) {
                    statusMapper.deleteByPrimaryKey(statusVO.getId());
                    continue;
                }
                if (!updateModelStatus(statusVO, model.getId())) {
                    result = false;
                }
                try {
                    String reportId = modelVO.getImportReportGuid();
                    if (StringUtils.isEmpty(reportId)) {
                        RireRiskWarningStatus rireRiskWarningStatus = mapper.selectByPrimaryKey(modelVO.getImportReportGuid());
                        reportId = rireRiskWarningStatus.getId();
                    }
                    waringService.generalModelCalculate(reportId);
                } catch (Exception e) {
                    log.info("保存模型时，模型计算失败：" + e.getMessage());
                }
            }
        }
        // endregion
        // region 自定义模型
        else {
            // TODO: 删除常见模型下的 预警状态 预警规则 预警指标
            // 修改披露报告主表的预警状态
            String warningStatus = modelVO.getWarningStatus();
            RireRiskWarningStatus rireRiskWarningStatus = mapper.selectByPrimaryKey(modelVO.getImportReportGuid());
            rireRiskWarningStatus.setWaringStatus(warningStatus);
            mapper.updateByPrimaryKeySelective(rireRiskWarningStatus);
        }
        // endregion
        if (result) {
            return getModel(model.getImportReportGuid(), false);
        }
        return null;
    }


    /**
     * 修改模型预警状态
     *
     * @param statusVO 从前台传过来的预警状态VO参数
     * @param modelId  模型ID
     * @return
     */
    private Boolean updateModelStatus(RiwaRiskWaringVO.RiwaRiskWaringStatusVO statusVO, String modelId) {
        RiwaRiskWaringStatus status = new RiwaRiskWaringStatus();
        BeanUtils.copyBeanProp(status, statusVO);
        status.setWarningModelGuid(modelId);
        // 是新增还是修改
        if (statusMapper.selectByPrimaryKey(statusVO.getId()) == null) {
            BeanUtils.initBean(status);
            if (statusMapper.insert(status) < 1) {
                log.error("披露报告模型-预警状态 新增失败！");
                return false;
            }

        } else {
            BeanUtils.updateBean(status);
            if (statusMapper.updateByPrimaryKey(status) < 1) {
                log.error("披露报告模型-预警状态 修改失败！");
                return false;
            }
        }
        // 模型预警规则
        for (RiwaRiskWaringRuleVO ruleVO : statusVO.getRiskWaringRuleVOList()) {
            if (!updateRules(ruleVO, status)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 修改模型预警规则
     *
     * @param ruleVO 从前台传过来的规则VO参数
     * @param status 预警状态
     * @return
     */
    private Boolean updateRules(RiwaRiskWaringRuleVO ruleVO, RiwaRiskWaringStatus status) {
        RiwaRiskWaringRule rule = new RiwaRiskWaringRule();
        BeanUtils.copyBeanProp(rule, ruleVO);
        rule.setWarningModelGuid(status.getWarningModelGuid());
        rule.setWaringStatusGuid(status.getId());
        // 是新增还是修改
        if (ruleMapper.selectByPrimaryKey(ruleVO.getId()) == null) {
            BeanUtils.initBean(rule);
            if (ruleMapper.insert(rule) < 1) {
                log.error("披露报告模型-预警规则 新增失败！");
                return false;
            }
        } else {
            BeanUtils.updateBean(rule);
            if (ruleMapper.updateByPrimaryKey(rule) < 1) {
                log.error("披露报告模型-预警规则 修改失败！");
                return false;
            }
        }
        // 模型预警规则指标
        for (RiwaRiskWaringTarget ruleTarget : ruleVO.getRiskWaringTargetList()) {
            if (!updateRuleTarget(ruleTarget, rule)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 修改模型预警规则指标
     *
     * @param ruleTarget 从前台传过来的指标参数
     * @param rule       模型预警规则
     * @return
     */
    private Boolean updateRuleTarget(RiwaRiskWaringTarget ruleTarget, RiwaRiskWaringRule rule) {
        ruleTarget.setWarningModelGuid(rule.getWarningModelGuid());
        ruleTarget.setWaringStatusGuid(rule.getWaringStatusGuid());
        ruleTarget.setWarningRuleId(rule.getId());
        // 是新增还是修改
        if (ruleTargetMapper.selectByPrimaryKey(ruleTarget.getId()) == null) {
            BeanUtils.initBean(ruleTarget);
            if (ruleTargetMapper.insert(ruleTarget) < 1) {
                log.error("披露报告模型-预警指标 新增失败！");
                return false;
            }

        } else {
            BeanUtils.updateBean(ruleTarget);
            if (ruleTargetMapper.updateByPrimaryKey(ruleTarget) < 1) {
                log.error("披露报告模型-预警指标 修改失败！");
                return false;
            }
        }
        return true;
    }

    // endregion

    // region 删除相关业务

    /**
     * 删除披露报告风险指标
     *
     * @param targets 风险指标集合
     * @return
     */
    @Override
    public Boolean deleteTarget(List<RireRiskTarget> targets) {
        Integer result = 0;
        for (RireRiskTarget target : targets) {
            if (targetMapper.deleteByPrimaryKey(target.getId()) > 0) {
                result++;
            }
        }
        return result > 0;
    }

    /**
     * 删除披露报告风险事件
     *
     * @param events 风险事件集合
     * @return
     */
    @Override
    public Boolean deleteEvent(List<RireRiskEvent> events) {
        Integer result = 0;
        for (RireRiskEvent event : events) {
            if (eventMapper.deleteByPrimaryKey(event.getId()) > 0) {
                result++;
            }
        }
        return result > 0;
    }

    /**
     * 删除披露报告模型规则
     *
     * @param rules 模型规则集合
     * @return
     */
    @Override
    public Boolean deleteModelRule(List<RiwaRiskWaringRule> rules) {
        Integer result = 0;
        for (RiwaRiskWaringRule rule : rules) {
            if (ruleMapper.deleteByPrimaryKey(rule.getId()) > 0) {
                // 删除规则下所有指标
                ruleTargetMapper.deleteByRuleId(rule.getId());
                result++;
            }
        }
        return result > 0;
    }

    /**
     * 删除披露报告模型规则指标
     *
     * @param targets 模型规则指标集合
     * @return
     */
    @Override
    public Boolean deleteModelTarget(List<RiwaRiskWaringTarget> targets) {
        Integer result = 0;
        for (RiwaRiskWaringTarget target : targets) {
            if (ruleTargetMapper.deleteByPrimaryKey(target.getId()) > 0) {
                result++;
            }
        }
        return result > 0;
    }

    @Override
    public Integer updateCompFlag(RireRiskTarget target) {
        return targetMapper.updateByPrimaryKeySelective(target);
    }

    @Override
    public Map pushWarningStatusData(String warningId) {
        Map returnMap=new HashMap();
        returnMap.put("status","1");
        returnMap.put("msg","推送成功");
        try {
            RireRiskWarningStatus warningStatusParam = new RireRiskWarningStatus();
            warningStatusParam.setId(warningId);
            RireRiskWarningStatus statusVO=rireRiskWarningStatusMapper.selectOne(warningStatusParam);
            //根据管理单位、年度、季度、父节点（parentId 不为空）获取重点风险表（T_RIIM_RISK_IMPORT）
            RiimRiskImportVO paramImport = new RiimRiskImportVO();
            paramImport.setAcctYear(statusVO.getAcctYear());
            paramImport.setManageCompCode(statusVO.getManageCompCode());
            List<RiimRiskImport> importList = riskImportMapper.selectManages(paramImport);
            if (importList.size() > 0) {
                for (RiimRiskImport item : importList) {
                    RireRiskWarningStatus subParam = new RireRiskWarningStatus();
                    subParam.setImportGuid(item.getId());
                    subParam.setAcctYear(statusVO.getAcctYear());
                    subParam.setQuarterCode(statusVO.getQuarterCode());
                    RireRiskWarningStatus subReport = rireRiskWarningStatusMapper.selectOne(subParam);
                    if (!ObjectUtils.isEmpty(subReport)) {
                        RiimRiskImport riskImport = new RiimRiskImport();
                        riskImport.setId(item.getParentId());
                        //根据parentId获取上级点位的重点风险
                        RiimRiskImport parentRiskImport = riskImportMapper.selectById(riskImport);
                        //根据重点风险ID、年度、季度，获取上级单位的监控报告
                        RireRiskWarningStatus statusParam = new RireRiskWarningStatus();
                        statusParam.setImportGuid(parentRiskImport.getId());
                        statusParam.setAcctYear(statusVO.getAcctYear());
                        statusParam.setQuarterCode(statusVO.getQuarterCode());
                        List<RiskWarningStatusVO> parentReport = rireRiskWarningStatusMapper.selectList(statusParam, null);
                        for (RiskWarningStatusVO warningStatusVO : parentReport) {
                            //如果上级单位监控报告的当前节点为待填报，则执行数据复制、调用上级单位工作流；如果上级单的当前节点已经汇总（B05\ B07\ B08\ B09）不复制数据，
                            //不调用上级单位工作流；如果上级单位的当前节点为其他，则提示“宝钢股份重点风险监控报告的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流”
                            if ("A01".equals(warningStatusVO.getStatus())) {
                                if (StringUtils.isNotEmpty(parentRiskImport.getDutyUserCode())) {
                                    this.copyData(warningStatusVO, statusVO);
                                    this.submit(parentRiskImport, warningStatusVO);
                                }

                            } else if ("B05".equals(warningStatusVO.getStatus()) || "B07".equals(warningStatusVO.getStatus()) || "B08".equals(warningStatusVO.getStatus()) || "B09".equals(warningStatusVO.getStatus())) {
                                returnMap.put("status","0");
                                returnMap.put("msg","宝钢股份重点风险监控报告的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流！");
                                return returnMap;
                            }
                        }
                    }
                }

            }


        } catch (Exception e) {
            log.error("扭转流程异常：" + e.getMessage());
            returnMap.put("status","0");
            returnMap.put("msg","宝钢股份重点风险监控报告的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流！");
            return returnMap;
        }

        return returnMap;
    }

    private void submit(RiimRiskImport parentRiskImport, RiskWarningStatusVO statusVO) {
        if (StringUtils.isNotEmpty(parentRiskImport.getDutyUserCode())) {
            XtzyUser xtzyUser = xtzyUserMapper.selectByName(parentRiskImport.getDutyUserCode());
            FltdTaskVO paramTask = new FltdTaskVO();
            paramTask.setFlowNo("fengxianpilubaogao");
            paramTask.setBizGuid(statusVO.getId());
            paramTask.setNodeCode(statusVO.getStatus());
            paramTask.setStatus("open");
            List<FltdTask> taskList = fltdTaskMapper.selectTaskList(paramTask);
            if (taskList.size() > 0) {
                FltdTaskVO taskVoParam = new FltdTaskVO();
                BeanUtils.copyBeanProp(taskVoParam, taskList.get(0));
                try {
                    FltdTask updateTask = new FltdTask();
                    updateTask.setTodoGuid(taskVoParam.getTodoGuid());
                    //走绿色通道
                    updateTask.setGreenFlag("G");
                    fltdTaskMapper.updateByPrimaryKeySelective(updateTask);
                    taskVoParam.setGreenFlag("G");

                    //获取下一节点审批人
                    Map<String, Object> resultMap = flaaNodeAuthoService.getNextUser(taskVoParam, xtzyUser);
                    List<XtzyUser> authUsers = (List<XtzyUser>) resultMap.get("authUsers");
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(authUsers)) {
                        taskVoParam.setCustomUsers(authUsers);

                        //查询指定节点的下一个节点及转移路线
                        String processDefId = fltdProcessService.getProcessDefId(taskVoParam.getProcGuid());
                        NodeTransitionVO nextTransition = flaaNodeAuthoMapper.nextOneNodeTransition(processDefId, "submit-G-1");
                        taskVoParam.setSubmitButton(nextTransition);

                        fltdProcessService.doSubmit(xtzyUser, taskVoParam);
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }


    private void copyData(RiskWarningStatusVO parentVo, RireRiskWarningStatus subVO) {
        //修改监控报告（T_RIRE_RISK_WARNING_STATUS）
        RireRiskWarningStatus updateParam = new RireRiskWarningStatus();
        updateParam.setId(parentVo.getId());
        RireRiskWarningStatus updateEntity = rireRiskWarningStatusMapper.selectOne(updateParam);
        updateEntity.setWarningAccording(subVO.getWarningAccording());
        updateEntity.setNextWaringStatus(subVO.getNextWaringStatus());
        updateEntity.setStrategy(subVO.getStrategy());
        updateEntity.setWaringStatus(subVO.getWaringStatus());
        rireRiskWarningStatusMapper.updateByPrimaryKey(updateEntity);
        subVO.setExt5(parentVo.getId());
        rireRiskWarningStatusMapper.updateByPrimaryKey(subVO);
        //删除上级单位股份的风险指标
        targetMapper.deleteByImportId(parentVo.getId());
        // 复制风险指标（T_RIRE_RISK_TARGET）
        List<RireRiskTarget> sourceImportData = targetMapper.getTargetByImportId(subVO.getId());
        for (RireRiskTarget item : sourceImportData) {
            RireRiskTarget targetRisk = new RireRiskTarget();
            BeanUtils.copyBeanProp(targetRisk, item);
            BeanUtils.initBean(targetRisk);
            targetRisk.setManageCompCode(parentVo.getManageCompCode());
            targetRisk.setManageCompName(parentVo.getManageCompName());
            targetRisk.setImportReportGuid(parentVo.getId());
            targetRisk.setImportGuid(parentVo.getImportGuid());
            targetMapper.insert(targetRisk);
        }
        //删除上级单位股份的风险事件
        rireRiskEventMapper.deleteByImportId(parentVo.getId());
        // 复制风险事件（T_RIRE_RISK_EVENT）
        List<RireRiskEvent> riskEventList = rireRiskEventMapper.getEventByImportId(subVO.getId());
        for (RireRiskEvent item : riskEventList) {
            RireRiskEvent riskEvent = new RireRiskEvent();
            BeanUtils.copyBeanProp(riskEvent, item);
            BeanUtils.initBean(riskEvent);
            riskEvent.setManageCompCode(parentVo.getManageCompCode());
            riskEvent.setManageCompName(parentVo.getManageCompName());
            riskEvent.setImportGuid(parentVo.getImportGuid());
            riskEvent.setImportReportGuid(parentVo.getId());
            rireRiskEventMapper.insert(riskEvent);
        }
        //删除上级单位股份的预警模型
        riwaRiskWaringMapper.deleteByImportId(parentVo.getId());
        // 复制预警模型（T_RIWA_RISK_WARING）
        List<RiwaRiskWaring> riwaRiskWaringList = riwaRiskWaringMapper.getWaringByImportId(subVO.getId());

        List<RiwaRiskWaring> parentWaringList = riwaRiskWaringMapper.getWaringByImportId(parentVo.getId());
        for (RiwaRiskWaring parentWaring : parentWaringList) {
            //删除预警模型-预警状态
            riwaRiskWaringStatusMapper.deleteByWaringId(parentWaring.getId());
            //删除重点风险预警模型-预警规则
            riwaRiskWaringRuleMapper.deleteByWaringId(parentWaring.getId());
            //删除重点风险预警模型-预警指标
            riwaRiskWaringTargetMapper.deleteByWaringId(parentWaring.getId());
        }
        for (RiwaRiskWaring item : riwaRiskWaringList) {
            RiwaRiskWaring riskWaring = new RiwaRiskWaring();
            BeanUtils.copyBeanProp(riskWaring, item);
            BeanUtils.initBean(riskWaring);
            riskWaring.setManageCompCode(parentVo.getManageCompCode());
            riskWaring.setManageCompName(parentVo.getManageCompName());
            riskWaring.setImportGuid(parentVo.getImportGuid());
            riskWaring.setImportReportGuid(parentVo.getId());
            riwaRiskWaringMapper.insert(riskWaring);
            //复制重点风险预警模型-预警状态T_RIWA_RISK_WARING_STATUS
            List<RiwaRiskWaringStatus> riskWaringStatusList = riwaRiskWaringStatusMapper.getWaringStatusByWaringId(item.getId());
            for (RiwaRiskWaringStatus statusItem : riskWaringStatusList) {
                RiwaRiskWaringStatus riskWaringStatus = new RiwaRiskWaringStatus();
                BeanUtils.copyBeanProp(riskWaringStatus, statusItem);
                BeanUtils.initBean(riskWaringStatus);
                riskWaringStatus.setImportGuid(parentVo.getImportGuid());
                riskWaringStatus.setWarningModelGuid(riskWaring.getId());
                riwaRiskWaringStatusMapper.insert(riskWaringStatus);
                //复制--重点风险预警模型-预警规则（T_RIWA_RISK_WARING_RULE）
                List<RiwaRiskWaringRule> waringRule = riwaRiskWaringRuleMapper.getWaringRuleByStatusId(statusItem.getId());
                for (RiwaRiskWaringRule ruleItem : waringRule) {
                    RiwaRiskWaringRule riskWaringRule = new RiwaRiskWaringRule();
                    BeanUtils.copyBeanProp(riskWaringRule, ruleItem);
                    BeanUtils.initBean(riskWaringRule);
                    riskWaringRule.setImportGuid(parentVo.getImportGuid());
                    riskWaringRule.setWaringStatusGuid(riskWaringStatus.getId());
                    riskWaringRule.setWarningModelGuid(riskWaring.getId());
                    riwaRiskWaringRuleMapper.insert(riskWaringRule);
                    //复制重点风险预警模型-预警指标（T_RIWA_RISK_WARING_TARGET）
                    List<RiwaRiskWaringTarget> waringTargetList = riwaRiskWaringTargetMapper.getWaringTargetByRuleId(ruleItem.getId());
                    for (RiwaRiskWaringTarget targetItem : waringTargetList) {
                        RiwaRiskWaringTarget riskWaringTarget = new RiwaRiskWaringTarget();
                        BeanUtils.copyBeanProp(riskWaringTarget, targetItem);
                        BeanUtils.initBean(riskWaringTarget);
                        riskWaringTarget.setImportGuid(parentVo.getImportGuid());
                        riskWaringTarget.setWarningModelGuid(riskWaring.getId());
                        riskWaringTarget.setWaringStatusGuid(riskWaringStatus.getId());
                        riskWaringTarget.setWarningRuleId(riskWaringRule.getId());
                        riwaRiskWaringTargetMapper.insert(riskWaringTarget);
                    }
                }

            }
        }
    }
}
